<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        .box{width:100px;height:100px;background:red;position: absolute;left:0;top:0;}
    </style>
</head>
<body>
    <div class="box"></div>
</body>
<script>
    class Drag{
        constructor(){
            this.ele = document.querySelector(".box");

            // 提前处理将来要作为事件处理函数使用的方法中的this
            this.m = this.move.bind(this);
            this.u = this.up.bind(this);
            this.d = this.down.bind(this);

            this.addEvent();
            this.setPos();
        }
        setPos(){
            this.ele.style.left = localStorage.getItem("x") + "px";
            this.ele.style.top = localStorage.getItem("y") + "px";
        }
        addEvent(){
            this.ele.addEventListener( "mousedown", this.d );
        }
        down(eve){
            console.log(3);
            this.downE = eve || window.event;
            document.addEventListener( "mousemove", this.m );
            document.addEventListener( "mouseup", this.u );
        }
        move(eve){
            this.moveE = eve || window.event;
            this.ele.style.left = this.moveE.pageX - this.downE.offsetX + "px";
            this.ele.style.top = this.moveE.pageY - this.downE.offsetY + "px";
        }
        up(){
            // 删除事件监听式绑定的事件的特点：
            // 要求：删除的事件处理函数和绑定的事件处理函数必须是同一个

            // bind的特点：
            // 返回值，改变了this指向之后的新函数
            document.removeEventListener( "mousemove", this.m );
            document.removeEventListener( "mouseup", this.u );

            localStorage.setItem("x", this.ele.offsetLeft);
            localStorage.setItem("y", this.ele.offsetTop);
        }
    }

    // 问题1：this指向
    // 问题2：删除事件监听式绑定的事件
    // 问题3：bind的返回值

    new Drag;
</script>
</html>